package com.ssyx.service.impl;

import com.ssyx.enums.PaymentStatus;
import com.ssyx.enums.PaymentType;
import com.ssyx.model.order.PaymentInfo;
import com.ssyx.service.PaymentInfoService;
import com.ssyx.service.WeixinService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @program: ssyx-parent
 * @className: WeixinServiceImpl
 * @description: 类
 * @data: 2024/3/21 16:02
 * @author: ihu
 * @version: 1.0
 **/

@Slf4j
@Service
public class WeixinServiceImpl implements WeixinService {
	@Resource
	private PaymentInfoService paymentService;
	@Resource
	private RedisTemplate<String, Object> redisTemplate;
	
	/**
	 * 根据订单号下单，生成支付链接
	 */
	@Override
	public Map<String, String> createJsapi(String orderNo) {
		PaymentInfo paymentInfo = paymentService.getPaymentInfo(orderNo, PaymentType.WEIXIN.getCode());
		if (paymentInfo == null) {
			paymentInfo = paymentService.savePaymentInfo(orderNo, PaymentType.WEIXIN.getCode());
		}
		if (paymentInfo.getPaymentStatus().equals(PaymentStatus.UNPAID.getCode())) {
			paymentService.paySuccess(orderNo, PaymentType.WEIXIN.getCode(), null);
		}
		//返回结果
		Map<String, String> result = new HashMap<>();
		result.put("timeStamp", new Date().toString());
		result.put("nonceStr", "nonceStr");
		result.put("signType", "MD5");
		result.put("paySign", PaymentType.WEIXIN.getComment());
		result.put("package", "packages");
		return result;
//		try {
//			Map<String, String> payMap = (Map<String, String>) redisTemplate.opsForValue().get(orderNo);
//			if (payMap != null) return payMap;
//
//			PaymentInfo paymentInfo = paymentService.getPaymentInfo(orderNo, PaymentType.WEIXIN);
//			if (paymentInfo == null) {
//				paymentInfo = paymentService.savePaymentInfo(orderNo, PaymentType.WEIXIN);
//			}
//
//			Map<String, String> paramMap = new HashMap<>();
//			//1、设置参数
//			paramMap.put("appid", ConstantPropertiesUtils.APPID);
//			paramMap.put("mch_id", ConstantPropertiesUtils.PARTNER);
//			paramMap.put("nonce_str", WXPayUtil.generateNonceStr());
//			paramMap.put("body", paymentInfo.getSubject());
//			paramMap.put("out_trade_no", paymentInfo.getOrderNo());
//			int totalFee = paymentInfo.getTotalAmount().multiply(new BigDecimal(100)).intValue();
//			paramMap.put("total_fee", String.valueOf(totalFee));
//			paramMap.put("spbill_create_ip", "127.0.0.1");
//			paramMap.put("notify_url", ConstantPropertiesUtils.NOTIFYURL);
//			paramMap.put("trade_type", "JSAPI");
////			paramMap.put("openid", "o1R-t5trto9c5sdYt6l1ncGmY5iY");
//			UserLoginVo userLoginVo = (UserLoginVo) redisTemplate.opsForValue().get("user:login:" + paymentInfo.getUserId
//			());
//			if (null != userLoginVo && !StringUtils.isEmpty(userLoginVo.getOpenId())) {
//				paramMap.put("openid", userLoginVo.getOpenId());
//			} else {
//				paramMap.put("openid", "oD7av4igt-00GI8PqsIlg5FROYnI");
//			}
//			// HTTPClient来根据URL访问第三方接口并且传递参数
//			HttpClient client = new HttpClient("https://api.mch.weixin.qq.com/pay/unifiedorder");
//			//client设置参数
//			client.setXmlParam(WXPayUtil.generateSignedXml(paramMap, ConstantPropertiesUtils.PARTNERKEY));
//			client.setHttps(true);
//			client.post();
//			//3、返回第三方的数据
//			String xml = client.getContent();
//			Map<String, String> resultMap = WXPayUtil.xmlToMap(xml);
//			log.info("微信下单返回结果：{}", JSON.toJSONString(resultMap));
//
//			// 再次封装参数
//			Map<String, String> parameterMap = new HashMap<>();
//			String prepayId = String.valueOf(resultMap.get("prepay_id"));
//			String packages = "prepay_id=" + prepayId;
//			parameterMap.put("appId", ConstantPropertiesUtils.APPID);
//			parameterMap.put("nonceStr", resultMap.get("nonce_str"));
//			parameterMap.put("package", packages);
//			parameterMap.put("signType", "MD5");
//			parameterMap.put("timeStamp", String.valueOf(new Date().getTime()));
//			String sign = WXPayUtil.generateSignature(parameterMap, ConstantPropertiesUtils.PARTNERKEY);
		
		//返回结果
//			Map<String, String> result = new HashMap<>();
//			result.put("timeStamp", parameterMap.get("timeStamp"));
//			result.put("nonceStr", parameterMap.get("nonceStr"));
//			result.put("signType", "MD5");
//			result.put("paySign", sign);
//			result.put("package", packages);
//			if (resultMap.get("result_code") != null) {
//				//微信支付二维码2小时过期，可采取2小时未支付取消订单
//				redisTemplate.opsForValue().set(orderNo, result, GlobalConstant.INTEGER_TWO, TimeUnit.HOURS);
//			}
//			return result;
//		} catch (Exception e) {
//			log.error("微信下单失败:{}", e.getMessage());
//			return new HashMap<>();
//		}
	}
	
	@Override
	public String queryPayStatus(String orderNo, String paymentType) {
		PaymentInfo paymentInfo = paymentService.getPaymentInfo(orderNo, PaymentType.WEIXIN.getCode());
		if (paymentInfo.getPaymentStatus().equals(PaymentStatus.PAID.getCode())) {
			return "支付成功";
		} else if (paymentInfo.getPaymentStatus().equals(PaymentStatus.UNPAID.getCode())) {
			return "支付中";
		} else {
			return "支付失败";
		}


//		try {
//			//1、封装参数
//			Map<String, String> paramMap = new HashMap<>();
//			paramMap.put("appid", ConstantPropertiesUtils.APPID);
//			paramMap.put("mch_id", ConstantPropertiesUtils.PARTNER);
//			paramMap.put("out_trade_no", orderNo);
//			paramMap.put("nonce_str", WXPayUtil.generateNonceStr());
//			//2、设置请求
//			HttpClient client = new HttpClient("https://api.mch.weixin.qq.com/pay/orderquery");
//			client.setXmlParam(WXPayUtil.generateSignedXml(paramMap, ConstantPropertiesUtils.PARTNERKEY));
//			client.setHttps(true);
//			client.post();
//			//3、返回第三方的数据
//			String xml = client.getContent();
//			Map<String, String> resultMap = WXPayUtil.xmlToMap(xml);
//			if (resultMap == null) {
//				log.error("微信支付查询失败");
//				throw new SsyxException(ResultCodeEnum.FAIL);
//			}
//			if ("SUCCESS".equals(resultMap.get("trade_state"))) {//如果成功
//				//更改订单状态，处理支付结果
//				String out_trade_no = resultMap.get("out_trade_no");
//				paymentService.paySuccess(out_trade_no, PaymentType.WEIXIN, resultMap);
//				return "支付成功";
//			}
//			return "支付中";
//		} catch (Exception e) {
//			log.error("微信支付查询失败:{}", e.getMessage());
//			throw new SsyxException(ResultCodeEnum.FAIL);
//		}
	}
}
